package land_register;


import java.io.IOException;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Clock;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.json.JSONObject;

import DB.DB_connection_pool;


public class Register_handle extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String nickname = request.getParameter("nickname");    //昵称
		String autograph = request.getParameter("autograph");    //签名
		String password = request.getParameter("password");     //密码
		String phone = request.getParameter("phone");           //手机号
		
		Clock clock = Clock.systemUTC();
		String user_account = String.valueOf((int)(Math.random()*90000)+10000)+clock.millis();      //产生用户账号
		
		//System.out.println(user_account);
		
		PrintWriter out = response.getWriter();       //获取输出流
		String insert_land_table_sql = "insert into land_table(user_account,user_password,user_telephone) values('"+user_account+"','"+password+"','"+phone+"')";    //登陆表
		String insert_user_data_sql = "insert into user_data(user_account,user_nickname,user_introduction,Is_telephone_checking) values('"+user_account+"','"+nickname+"','"+autograph+"','"+1+"')";   //用户信息表
		String phone_select = "select user_telephone from land_table where user_telephone='"+phone+"'";
		
		int tf=0;
		int tf_1=0;
		

		
		
		try {
			Connection db = DB_connection_pool.data_pool.getConnection();   //获取连接
			
			PreparedStatement ps_select= db.prepareStatement(phone_select);
			ResultSet rs =  ps_select.executeQuery();
			
			if(!rs.next()){ 
			PreparedStatement ps = db.prepareStatement(insert_land_table_sql);
			 tf = ps.executeUpdate();
			
			PreparedStatement ps_1 = db.prepareStatement(insert_user_data_sql);
		     tf_1 = ps_1.executeUpdate();
		     
		     ps.close();
		     ps_1.close();
			}
			
			JSONObject jsonObj = new JSONObject();
			if(tf>0&tf_1>0){
				jsonObj.put("user_account", user_account);
				
				out.print(jsonObj.toString());
			}
			else{
				out.print(jsonObj.toString());
			}
			
			
		
			rs.close();
			ps_select.close();
			out.close();
			db.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			//out.print("0");
			e.printStackTrace();
		}      
		
		
		
	
		
		

	}

}
